package com.ssw.backend.service.impl.user.bot;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ssw.backend.mapper.BotMapper;
import com.ssw.backend.pojo.Bot;
import com.ssw.backend.pojo.User;
import com.ssw.backend.service.bot.AddService;
import com.ssw.backend.service.impl.utils.UserDetailsImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AddServiceImpl implements AddService {
    @Autowired
    private BotMapper botMapper;
    @Override
    public Map<String, String> add(Map<String, String> data) {

        UsernamePasswordAuthenticationToken authenticationToken=
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl loginUser =(UserDetailsImpl) authenticationToken.getPrincipal();
        User user = loginUser.getUser();

        String title = data.get("title");
        String description = data.get("description");
        String content = data.get("content");

        Map<String,String > map=new HashMap<>();
        if(title.length()==0 || title==null){
            map.put("error_message","标题不能为空");
            return map;
        }
        if(title.length()>=100)
        {
            map.put("error_message","标题不能超过100");
            return map;
        }
        if(description.length()>=1000){
            map.put("error_message","描述不能超过1000");
            return map;
        }
        if(description.length()==0||description==null){
            description="这个用户很懒，什么都没有留下~";
        }
        if(content.length()==0 || content==null){
            map.put("error_message","代码不能为空");
            return map;
        }
        if(content.length()>=10000){
            map.put("error_message","代码长度不能超过10000");
            return map;
        }

        QueryWrapper queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",user.getId());
        if(botMapper.selectCount(queryWrapper)>=10){
            map.put("error_message","每个用户最多只能创建10个");
            return map;
        }

        Date now=new Date();
        Bot bot=new Bot(null,user.getId(),user.getUsername(),title,description,content,now,now);
        botMapper.insert(bot);
        map.put("error_message","success");
        return map;
    }
}
